{% extends "layouts/layout.html" %}
{% block title %}
{{ thread.title }}
{% endblock %}
{% block content %}

<h3>{{ thread.title }}
	{% if not(thread.external_conversation) %}
{% if thread.created_by_id == current_li.user_id %}
( <a href="/users/shop?user_id={{thread.recipient_id}}">{{ thread.get_recipient().get_display_name() }}</a> )
{% else %}
( <a href="/users/shop?user_id={{thread.created_by_id}}">{{ thread.get_creator().get_display_name() }}</a> )
{% endif %}
	{% endif %}
</h3>
{% if thread.item_details %}
  <p>{{ thread.item_details }} </p>
{% endif %}
<div class="well">
<table style="width:100%">

{% set tmp_parent = None %}
{% set first_message = True %}
{% set needs_close = False %}
{% for child in children %}
	{% set sender = child.get_sender() %}
	{% if sender.user_id != tmp_parent.user_id %}
		{% if first_message %}
			{% set needs_close = True %}
			{% set first_message = False %}
		{% else %}
			</table></td></tr>
		{% endif %}
		<tr>
			<td style="width:70px;">
				{% if sender.avatar %}
					<img src="/images/?avatar_id={{child.created_by_id}}" width="48" height="48"/>
				{% else %}
					<img src="/img/default_user.png" width="48" height="48" />
				{% endif %}
				
			</td>
			{% if sender %}
			<td><strong><a href="/users/shop?user_id={{sender.user_id}}">{{ sender.get_display_name()}}</a> (ID: {{child.get_sender().user_id}})</strong></td>
			{% else %}
			<td><strong>{{ child.created_by_id }}</strong></td>
			{% endif %}
		</tr>
		<tr>
			<td></td>
			<td><table class="table table-striped">
	{% endif %}
	<tr><td>{{ child.body }} (Sent: {{ child.created_at.strftime("%m/%d/%Y at %H:%M")}})</td></tr>
	{% set tmp_parent = child.get_sender() %}
{% endfor %}

{% if needs_close %}
</table></td></tr>
{% endif %}
</table>
</div>
<form action="/threads/save_message" method="post">
	<!-- FIXED: this isn't secure, since the user can modify the ID field and inject messages into other peoples threads -->
	<input type="hidden" name="thread_id" value="{{ thread.key().id() }}"/>
  <input type="hidden" name="xsrf_token" value="{{xsrf_token}}" />
	<label>Message:</label><textarea name="message" class="message_box" rows="4" cols="50"></textarea>
	<p>
		<button type="submit" value="submit" class="btn btn-primary">Reply</button>
		<a class="btn" href="/threads/">Back</a>
	</p>
</form>
{% endblock %}